package org.projectwithoutname.application;

import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class CriarThumbnail{
  
	/**
	   * Convenience method that save a scaled image
	   *
	   * @param orig : path of the original image to be scaled
	   * @param dest : path of the scaled image
	   * @param width : targetWidth the desired width of the scaled instance,
	   *    in pixels
	   * @param hieght : targetHeight the desired height of the scaled instance,
	   *    in pixels
	   * @param quality value between 10 - 100 to define a quality to new image  
	   * @param higherQuality if true, this method will use a multi-step
	   *    scaling technique that provides higher quality than the usual
	   *    one-step technique (only useful in downscaling cases, where
	   *    {@code targetWidth} or {@code targetHeight} is
	   *    smaller than the original dimensions, and generally only when
	   *    the {@code BILINEAR} hint is specified)
	   */
	public static void risize(String orig, String dest, int width, int height, int quality, boolean highQuality) throws Exception{
	    String mImagem = orig;
	    String fImagem = dest;
	
	    Image imagem = Toolkit.getDefaultToolkit().getImage(mImagem);
	    MediaTracker mediaTracker = new MediaTracker(new Container());
	    mediaTracker.addImage(imagem, 0);
	    mediaTracker.waitForID(0);
	    
	    int qualidade = quality; // 100%
	    int largura = width;
	    int altura = height;
	 
	    double thumbRatio = (double)largura / (double)altura;
	    int larguraImagem = imagem.getWidth(null);
	    int alturaImagem = imagem.getHeight(null);
	    double imageRatio = (double)larguraImagem / (double)alturaImagem;
	    if(thumbRatio < imageRatio){
	      altura = (int)(largura / imageRatio);
	    }
	    else{
	      largura = (int)(altura * imageRatio);
	    }
	
	    // Draw original image
	    BufferedImage thumbImage = new BufferedImage(imagem.getWidth(null), imagem.getHeight(null), BufferedImage.TYPE_INT_RGB);
	    Graphics2D graphics2D = thumbImage.createGraphics();
	    graphics2D.drawImage(imagem, 0, 0, imagem.getWidth(null), imagem.getHeight(null), null);
	    
	//  resize to avatar's size  
	    thumbImage = getScaledInstance(thumbImage, largura, altura, RenderingHints.VALUE_INTERPOLATION_BICUBIC, highQuality);
	    
	    /*FIX ME: find another way to save new image without sun's classes.
	     * save new image
	     */
	    BufferedOutputStream out = new BufferedOutputStream(new
	    FileOutputStream(fImagem));
	    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	    JPEGEncodeParam param = encoder.
	      getDefaultJPEGEncodeParam(thumbImage);
	    param.setQuality((float)qualidade / 100.0f, false);
	    encoder.setJPEGEncodeParam(param);
	    encoder.encode(thumbImage);
	    out.close();
     
	}
  
  
  /**
   * Convenience method that returns a scaled instance of the
   * provided {@code BufferedImage}.
   *
   * @param img the original image to be scaled
   * @param targetWidth the desired width of the scaled instance,
   *    in pixels
   * @param targetHeight the desired height of the scaled instance,
   *    in pixels
   * @param hint one of the rendering hints that corresponds to
   *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
   *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
   *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
   *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
   * @param higherQuality if true, this method will use a multi-step
   *    scaling technique that provides higher quality than the usual
   *    one-step technique (only useful in downscaling cases, where
   *    {@code targetWidth} or {@code targetHeight} is
   *    smaller than the original dimensions, and generally only when
   *    the {@code BILINEAR} hint is specified)
 * @param targetWidth 
   * @return a scaled version of the original {@code BufferedImage}
   */
  private static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality){
      int type = (img.getTransparency() == Transparency.OPAQUE) ?
          BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
      BufferedImage ret = (BufferedImage)img;
      int w, h;
      if (higherQuality) {
          // Use multi-step technique: start with original size, then
          // scale down in multiple passes with drawImage()
          // until the target size is reached
          w = img.getWidth();
          h = img.getHeight();
      } else {
          // Use one-step technique: scale directly from original
          // size to target size with a single drawImage() call
          w = targetWidth;
          h = targetHeight;
      }
      
      do {
          if (higherQuality && w > targetWidth) {
              w /= 2;
              if (w < targetWidth) {
                  w = targetWidth;
              }
          }

          if (higherQuality && h > targetHeight) {
              h /= 2;
              if (h < targetHeight) {
                  h = targetHeight;
              }
          }

          BufferedImage tmp = new BufferedImage(w, h, type);
          Graphics2D g2 = tmp.createGraphics();
          g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
          g2.drawImage(ret, 0, 0, w, h, null);
          g2.dispose();

          ret = tmp;
      } while (w != targetWidth || h != targetHeight);

      return ret;
  }
}